import React, { useEffect, useState } from 'react'
import { GetServerSideProps } from 'next/types'
import { useRouter } from 'next/router'
import { Divider } from '@mui/material'

import { getBlogListByTagName } from '@/api/tag'
import { TagPageWrap } from '@/components/pages/tag/styled'
import { PostList } from '@/components/PostList'
import MyPagination from '@/components/Pagination/Pagination'
import { setPageTitle } from '@/utils'
import { AppLayout } from '@/layout'

function TagPage({ data }) {
  const router = useRouter()
  const { tag } = router.query
  const { list, totalPage } = data
  const [pages, setPages] = useState(totalPage)
  const [postList, setPostList] = useState<any[]>(list)
  const [currentPage, setCurrentPage] = useState(1)

  const handleChange = async (event, value) => {
    setCurrentPage(value)
  }

  useEffect(() => {
    async function fetchData() {
      const res = await getBlogListByTagName(tag, currentPage)
      const { data } = res
      setPostList(data.list)
      setPages(data.totalPage)
    }

    fetchData()
  }, [currentPage, tag])

  useEffect(() => {
    setPageTitle(`${tag}下的文章`)
  }, [tag])

  return (
    <AppLayout>
      <TagPageWrap>
        <h3>{tag} </h3>
        <Divider />
        <PostList posts={postList} />
        <MyPagination
          list={postList}
          handleChange={handleChange}
          pages={pages}
          page={currentPage}
        />
      </TagPageWrap>
    </AppLayout>
  )
}

export const getServerSideProps: GetServerSideProps = async (context) => {
  const { query } = context
  const res = await getBlogListByTagName(query.tag, 1)
  return {
    props: {
      data: res.data,
    },
  }
}

export default TagPage
